const product = require("express").Router()

const sqlOptions = require("../../sql");

const nanoid = require("nanoid").nanoid

const handlerList = require("../../handler/handlerList");

const {rules, valid} = require("../../utils/rules");

const multer = require('multer')

const path = require("path");

const fs = require("fs");

const {handleImage} = require("../../handler/handleImage");

const dirPath = path.resolve(__dirname, '../../static/product/')

const productSave = [
    {
        name: "product_pic",
        message: "商品图片"
    },
    {
        name: "product_name",
        message: "商品名称"
    },
    {
        name: "category_id",
        message: "商品分类"
    },
    {
        name: "brand_id",
        message: "商品品牌"
    },
    {
        name: "product_count",
        message: "商品数量"
    },
    {
        name: "product_money",
        message: "商品价格"
    },
    {
        name: "product_address",
        message: "发货地址"
    },
]

const productUpdate = [].concat(productSave, [
    {
        name: "product_id",
        message: "商品id"
    }
])

const isHot = [
    {
        name: "product_id",
        message: "商品id"
    },
    {
        name: "hot",
        message: "推荐"
    },
]

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, dirPath); // 他会放在当前目录下的 /upload 文件夹下（没有该文件夹，就新建一个）
    },
    filename: function(req, file, cb) { // 在这里设定文件名
        cb(null, Date.now() + '-' + file.originalname); // file.originalname是将文件名设置为上传时的文件名，file中携带的
    }
})

product.post("/save", rules(productSave), valid, async (req, res) => {
    try {
        const data = req.body
        const hot = '0'
        const product_id = nanoid()

        const productSave = sqlOptions({
            name: "sms_product",
            method: "save",
            data: {
                ...data,
                hot,
                product_id
            }
        })
        await req.db.query(productSave)
        return res.status(200).send({
            code: 200,
            message: "添加成功",
            data: ''
        })

    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})
//更新
product.post("/update", async (req, res) => {
    try {
        const data = JSON.parse(JSON.stringify(req.body))
        const infoPics = data.infoPics.split(",")
        const productPic = data.picUrls.split(",")
        const infoList = data.infoList
        const list = await req.db.query(sqlOptions({
            name: "sms_product",
            method: "list",
            data: {
                product_id: data.product.product_id
            }
        }))
        console.log(list)
        if (list.length) {
            // 轮播图 更新
            const picurllist = await req.db.query(sqlOptions({
                name: "sms_product_pic",
                method: "list",
                data: {
                    product_id: data.product.product_id
                }
            }))
            if (picurllist.length) {
                await req.db.query(sqlOptions({
                    method: "delete",
                    name: "sms_product_pic",
                    data: {
                        product_id: data.product.product_id
                    }
                }))
            }
            await req.db.query(sqlOptions({
                method: "save",
                name: "sms_product_pic",
                data: productPic.map(item => ({
                    product_pic_url: item,
                    product_id: data.product.product_id
                }))
            }))
            // 详情图片表更新
            const productPicInfos = await req.db.query(sqlOptions({
                name: "sms_product_pic_info",
                method: "list",
                data: {
                    product_id: data.product.product_id
                }
            }))
            if (productPicInfos.length) {
                await req.db.query(sqlOptions({
                    method: "delete",
                    name: "sms_product_pic_info",
                    data: {
                        product_id: data.product.product_id
                    }
                }))
            }
            await req.db.query(sqlOptions({
                method: "save",
                name: "sms_product_pic_info",
                data: infoPics.map(item => ({
                    pic: item,
                    product_id: data.product.product_id
                }))
            }))
            // 详情表更新
            const productInfos = await req.db.query(sqlOptions({
                name: "sms_product_info",
                method: "list",
                data: {
                    product_id: data.product.product_id
                }
            }))
            if (productInfos.length) {
                await req.db.query(sqlOptions({
                    method: "delete",
                    name: "sms_product_info",
                    data: {
                        product_id: data.product.product_id
                    }
                }))
            }
            await req.db.query(sqlOptions({
                method: "save",
                name: "sms_product_info",
                data: infoList.map(item => ({
                    product_id: data.product.product_id,
                    ...item
                }))
            }))
            // 是否更新推荐表
            if (data.product.hot === "1") {
                // sms_recommend
                const recData = JSON.parse(JSON.stringify(data.product))
                delete recData.hot
                delete recData.id
                delete recData.product_id
                await req.db.query(sqlOptions({
                    name: 'sms_recommend',
                    method: "update",
                    key: {
                        product_id: data.product.product_id
                    },
                    data: recData
                }))
            }
            // 商品表更新
            await req.db.query(sqlOptions({
                name: 'sms_product',
                method: "update",
                key: {
                    product_id: data.product.product_id
                },
                data: data.product
            }))
            return res.status(200).send({
                code: 200,
                message: "修改成功",
                data: ''
            })
        }
        return res.status(200).send({
            code: 400,
            message: "没有这条信息无法删除",
            data: ''
        })
    } catch (e) {
        console.log(e)
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})
//删除
product.delete("/delete", async (req, res) => {
    try {
        const product_id = req.query.product_id
        const list = await req.db.query(sqlOptions({
            name: 'sms_product',
            method: "list",
            data: {
                product_id
            }
        }))
        if (list.length) {
            await req.db.query(sqlOptions({
                method: 'call',
                procedure: 'delete_row_product',
                value: product_id
            }))
            // 删除图片
            fs.unlinkSync(path.resolve(dirPath, list[0].product_pic))
            return res.status(200).send({
                code: 200,
                message: "删除成功",
                data: ""
            })
        }
        return res.status(200).send({
            code: 400,
            message: "当前列表没有该商品信息无法删除",
            data: ""
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})
//查询
product.post("/list", async (req, res) => {
//    sms_product
    try {
        const {current, pageSize, data} = req.body

        const [total] = await req.db.query(sqlOptions({
            name: 'sms_product',
            method: 'total'
        }))
        const list = await req.db.query(sqlOptions({
            key: 'product_name',
            like: true,
            name: 'sms_product',
            method: 'list',
            data,
            current,
            pageSize
        }))

        const brandList = await req.db.query(sqlOptions({
            name: 'sms_brand',
            method: 'list',
            data: {}
        }))
        const categoryList = await req.db.query(sqlOptions({
            name: 'sms_category',
            method: 'list',
            data: {}
        }))

        return res.status(200).send({
            code: 200,
            message: '',
            data: {
                current: current,
                pageSize: pageSize,
                total: total["COUNT(*)"],
                list: list.map(item => {
                    const obj = item
                    // brand_id
                    // category_id
                    obj.brand_name = brandList.filter(i => i.brand_id === item.brand_id)[0].brand_name
                    obj.category_name = categoryList.filter(i => i.category_id === item.category_id)[0].category_name
                    return obj
                })
            }
        })

    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})
// 添加折扣价格
product.post("/discount", async (req, res) => {
    try {
        const {discount, product_id} = req.body

        await req.db.query(sqlOptions({
            method: "update",
            name: "sms_product",
            key: {
                product_id
            },
            data: {
                discount
            }
        }))

        const list = await req.db.query(sqlOptions({
            name: "sms_recommend",
            method: "list",
            data: {
                product_id
            }
        }))
        if (list.length) {
            await req.db.query(sqlOptions({
                name: 'sms_recommend',
                method: "update",
                key: {
                    product_id
                },
                data: {
                    discount
                }
            }))
        }

        return res.status(200).send({
            code: 200,
            message: "折扣修改成功",
            data: ''
        })

    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})
// 是否推荐
product.post("/isHot", rules(isHot), valid, async (req, res) => {
    try {
        const {
            product_id,
            hot
        } = req.body
        if (hot === '0'){
            const recommendList = await req.db.query(sqlOptions({
                name: 'sms_recommend',
                method: 'list',
                data: {
                    product_id
                }
            }))
            if (recommendList.length) {
                await req.db.query(sqlOptions({
                    method: 'delete',
                    name: 'sms_recommend',
                    data: {
                        product_id
                    }
                }))
                await req.db.query(sqlOptions({
                    method: "update",
                    name: 'sms_product',
                    data: {
                        hot
                    },
                    key: {
                        product_id
                    }
                }))
                return res.status(200).send({
                    code: 200,
                    message: '修改成功',
                    data: ''
                })
            }
            return res.status(200).send({
                code: 400,
                message: '没有数据无法修改',
                data: ''
            })
        }
        if (hot === '1') {
            const productList = await req.db.query(sqlOptions({
                name: 'sms_product',
                method: 'list',
                data: {
                    product_id
                }
            }))
            await req.db.query(sqlOptions({
                method: "update",
                name: 'sms_product',
                data: {
                    hot
                },
                key: {
                    product_id
                }
            }))
            if (productList.length) {
                const recommend = JSON.parse(JSON.stringify(productList[0]))
                delete recommend.hot
                delete recommend.id
                delete recommend.createTime
                delete recommend.updateTime
                await req.db.query(sqlOptions({
                    name: 'sms_recommend',
                    method: 'save',
                    data: recommend
                }))

                return res.status(200).send({
                    code: 200,
                    message: '修改成功',
                    data: ''
                })
            }
            return res.status(200).send({
                code: 400,
                message: '没有数据无法修改',
                data: ''
            })
        }
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})
// 商品图片
product.post("/pic", multer({storage}).single('file'), handleImage)
// 删除图片
product.post("/pic/del", (req, res) => {
    try {
        const { url } = req.body
        fs.unlinkSync(path.resolve(dirPath, url))
        return res.status(200).send({
            code: '200',
            message: '图片删除成功',
            data: ""
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: '系统错误',
            data: ''
        })
    }
})
// 根据id查询表
product.get("/queryList", async (req, res) => {
    try {
        const product_id = req.query.id
        const productList = await req.db.query(sqlOptions({
            method: "list",
            data: {
                product_id
            },
            name: "sms_product"
        }))
        const brandList = await req.db.query(sqlOptions({
            name: 'sms_brand',
            method: 'list',
            data: {}
        }))
        const categoryList = await req.db.query(sqlOptions({
            name: 'sms_category',
            method: 'list',
            data: {}
        }))
        const product = productList.map(item => {
            const obj = item
            obj.brand_name = brandList.filter(i => i.brand_id === item.brand_id)[0].brand_name
            obj.category_name = categoryList.filter(i => i.category_id === item.category_id)[0].category_name
            return obj
        })[0]
        //颜色
        const colors = await req.db.query(sqlOptions({
            method: "list",
            data: {
                product_id
            },
            name: "sms_product_color"
        }))
        // 轮播图
        const pics = await req.db.query(sqlOptions({
            method: "list",
            data: {
                product_id
            },
            name: "sms_product_pic"
        }))
        // 详情图片
        const infoPics = await req.db.query(sqlOptions({
            method: "list",
            data: {
                product_id
            },
            name: "sms_product_pic_info"
        }))
        const productInfos = await req.db.query(sqlOptions({
            method: "list",
            data: {
                product_id
            },
            name: "sms_product_info"
        }))

        // console.log(productInfos, 1223456)
        return res.status(200).send({
            code: 200,
            message: "",
            data: {
                // 商品表数据
                product,
                // 商品颜色
                colors,
                // 轮播图
                pics,
                //商品图片
                infoPics,
                // 详情
                productInfos
            }
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: '系统错误',
            data: ''
        })
    }
})
// 颜色添加
const colorSave = [
    {
        name: "product_color_name",
        message: "颜色名称"
    },
    {
        name: "product_color_count",
        message: "商品库存"
    },
    {
        name: "product_color_pic",
        message: "颜色图片"
    },
    {
        name: "product_id",
        message: "商品id"
    }
]

product.post("/color/save", rules(colorSave), valid, async (req, res) => {
    try {
        const {
            product_id,
            product_color_name
        } = req.body
        const list = await req.db.query(sqlOptions({
            method: "list",
            name: 'sms_product_color',
            data: {
                product_id,
                product_color_name
            },
            if: "AND"
        }))
        if (list.length) {
            return res.status(200).send({
                code: 400,
                message: "名称重复",
                data: ""
            })
        }

        const productList = await req.db.query(sqlOptions({
            method: "list",
            name: "sms_product",
            data: {
                product_id
            }
        }))
        if (productList.length) {
            const colorList = await req.db.query(sqlOptions({
                method: "list",
                name: "sms_product_color",
                data: {
                    product_id
                }
            }))
            let count = Number(req.body.product_color_count)
            for (const item of colorList) {
                count += Number(item.product_color_count)
            }
            if (count <= productList[0].product_count) {
                await req.db.query(sqlOptions({
                    method: "save",
                    name: 'sms_product_color',
                    data: req.body
                }))
                return res.status(200).send({
                    code: 200,
                    message: "添加成功",
                    data: ""
                })
            }
            return res.status(200).send({
                code: 400,
                message: "当前所有颜色库存大于商品库存无法添加",
                data: ""
            })
        }
        return res.status(200).send({
            code: 400,
            message: "当前商品已被删除无法添加",
            data: ""
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: '系统错误',
            data: ''
        })
    }
})
const colorUpdate = [].concat(colorSave, [{
    name: "id",
    message: "颜色id"
}])
product.post("/color/update", rules(colorUpdate), valid, async (req, res) => {
    try {
        const {
            product_id,
            product_color_name,
            id
        } = req.body
        const productList = await req.db.query(sqlOptions({
            method: "list",
            name: "sms_product",
            data: {
                product_id
            }
        }))
        if (productList.length){
            const colorList = await req.db.query(sqlOptions({
                name: 'sms_product_color',
                method: "list",
                data: {
                    id
                }
            }))

            if (colorList.length) {
                const list = await req.db.query(sqlOptions({
                    method: "list",
                    name: 'sms_product_color',
                    data: {
                        product_id,
                        product_color_name
                    },
                    if: "AND"
                }))
                if (list.length) {
                    const colors = list.filter(item => item.id !== id)
                    console.log(colors)
                    if (colors.length) {
                        return res.status(200).send({
                            code: 400,
                            message: "名称重复",
                            data: ""
                        })
                    }
                }
                const colors = await req.db.query(sqlOptions({
                    method: "list",
                    name: "sms_product_color",
                    data: {
                        product_id
                    }
                }))
                // 总库存
                let count = Number(req.body.product_color_count)
                for (const item of colors) {
                    if (item.id !== id) {
                        count += Number(item.product_color_count)
                    }
                }
                console.log(count)
                if (count <= productList[0].product_count) {
                    await req.db.query(sqlOptions({
                        method: "update",
                        name: 'sms_product_color',
                        data: req.body,
                        key: {
                            id
                        }
                    }))
                    return res.status(200).send({
                        code: 200,
                        message: "修改成功",
                        data: ""
                    })
                }
                return res.status(200).send({
                    code: 400,
                    message: "当前所有颜色库存大于商品库存无法修改",
                    data: ""
                })
            }
            return res.status(200).send({
                code: 400,
                message: "当前商品没有该颜色无法修改",
                data: ""
            })
        }
        return res.status(200).send({
            code: 400,
            message: "当前商品已被删除无法修改",
            data: ""
        })

    } catch (e) {
        console.log(e)
        return res.status(500).send({
            code: 500,
            message: '系统错误',
            data: ''
        })
    }
})

product.get("/color/queryList", async (req, res) => {
    try {
        const {product_id} = req.query
        console.log(req.query)
        console.log(product_id)
        const colorList = await req.db.query(sqlOptions({
            method: "list",
            name: "sms_product_color",
            data: {
                product_id
            }
        }))
        // console.log(colorList)
        return res.status(200).send({
            code: 200,
            message: "",
            data: colorList
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: '系统错误',
            data: ''
        })
    }
})

product.delete("/color/delete", async (req, res) => {
    try {
        const {id} = req.query
        await req.db.query(sqlOptions({
            method: "delete",
            name: 'sms_product_color',
            data: {
                id
            }
        }))
        return res.status(200).send({
            code: 200,
            message: "删除成功",
            data: ""
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: '系统错误',
            data: ''
        })
    }
})


module.exports = product
